package algebra.query.indexing;

import java.util.HashMap;
import java.util.Map;

import utils.exception.OrderingDescriptionException;
import utils.exception.SyntaxParsingException;
import utils.parser.Creator;
import utils.parser.Parser;

import algebra.query.indexing.DescriptionIndex;
import algebra.query.od.OrderDep;
import algebra.query.pd.ProjDesc;
import utils.io.LoadWebFile;
import entities.concept.Concept;
import kb.DescriptionLogicsKB;

@Deprecated
public class SerializeIndices {

	public static int indexCount = 0;
	public static Map<String, String> allIndicesNames = new HashMap<String, String>();
	private static boolean verbose = true;
	public static final String dir = ""; // e.g."/Projects/WebDeployment/system/indices/"

	public static void main(String[] args) {
		generateSampleSIs(true,
				"http://localhost/system/kb/dc/Canon_DPC_1_5.kbox");
	}

	public static Map<String, String> generateSampleSIs(boolean export,
			String webloc) {
		// c, pd, od
		String[][] params = {
				{
						" (not (< (role user_review) 3.50) )",
						"(pd-and (pd-feature num_user_review) (pd-feature user_review))",
						"(od-feature user_review un)" },
				{
						"(exists (role hasInstance) (exists (role hasSale) (not (< (role price) 05500.00) )) )",
						"(pd-role hasInstance (pd-role hasSale (pd-feature price)))",
						"(od-feature price un)" } };
		// get KB
		LoadWebFile loader = new LoadWebFile(webloc, false);
		loader.resolveFile();
		DescriptionLogicsKB kb = loader.getKB();
		// to build a given index, we need KB, C, Pd, Od
		for (String[] one : params) {
			Concept c = null;
			ProjDesc pd = null;
			OrderDep od = null;
			try {
				c = Parser.conParser(
						Parser.getListOfTokensFromTokenizer(one[0]), kb);
				pd = Creator.createProjDesc(Parser
						.getListOfTokensFromTokenizer(one[1]), kb);
				od = OrderDep.getOrderDep(one[2]);
			} catch (SyntaxParsingException e) {
				e.printStackTrace();
			}
			generateOneIndex(kb, c, pd, od, export, "");
		}
		return allIndicesNames;

	}

	private static String indexNamePrefix = "SI_";

	public static DescriptionIndex generateOneIndex(DescriptionLogicsKB kb,
			Concept c, ProjDesc pd, OrderDep od,
			boolean serialize, String encoding) {
		DescriptionIndex di = null;
		SecondaryIndex si = new SecondaryIndex(c, pd, od, kb);
		String shortname = indexNamePrefix + indexCount++;
		allIndicesNames.put(shortname, si.getName());
		if (verbose) {
			System.out.printf("\nStart building %s ... \n", shortname);
			System.out.println(si.getName());
		}
		long sitime = System.currentTimeMillis();
		si.buildIndex(null);
		di = si.getDescriptionIndex();
		System.err.printf("Finished: %f seconds\n",
				(System.currentTimeMillis() - sitime) / 1000.0);
		if (serialize) {
			// export as files
			CachedIndex.serializeCacheIndex(si.toSerializedString(), di,
					encoding, dir + si.getName());
		}
		return di;
	}

}
